package com.hotely5d.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.hotely5d.dao.CategoryMapper;
import com.hotely5d.dao.RoomMapper;
import com.hotely5d.entity.Category;
import com.hotely5d.entity.Room;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private RoomMapper roomMapper;

    public List<Category> findAll() {
        // 只查询未删除的房型
        List<Category> categories = categoryMapper.selectList(new EntityWrapper<Category>().eq("deleted", 0));
        for (Category category : categories) {
            Integer count = roomMapper.selectCount(new EntityWrapper<Room>().eq("category_id", category.getId()).eq("status", 1).eq("deleted", 0));
            category.setRoomNum(count);
        }
        return categories;
    }

    public Page<Category> search(Page<Category> page,Category category) {
        List<Category> list = categoryMapper.selectPage(page, getEntityWrapper(category));
        for (Category c : list) {
            Integer count = roomMapper.selectCount(new EntityWrapper<Room>().eq("category_id", c.getId()).eq("status", 1).eq("deleted", 0));
            c.setRoomNum(count);
        }
        return page.setRecords(list);
    }

    public List<Category> search(Category category) {
        List<Category> list = categoryMapper.selectList(getEntityWrapper(category));
        for (Category c : list) {
            Integer count = roomMapper.selectCount(new EntityWrapper<Room>().eq("category_id", c.getId()).eq("status", 1).eq("deleted", 0));
            c.setRoomNum(count);
        }
        return list;
    }

    //条件构造器
    private EntityWrapper<Category> getEntityWrapper(Category category){
        EntityWrapper<Category> entityWrapper = new EntityWrapper<>();
        // 只查询未删除的房型
        entityWrapper.eq("deleted", 0);
        if(null != category){
            if(!StringUtils.isEmpty(category.getCategoryName())){
                entityWrapper.like("category_name",String.valueOf(category.getCategoryName()));
            }
            if(!StringUtils.isEmpty(category.getPhoto())){
                entityWrapper.like("photo",String.valueOf(category.getPhoto()));
            }
            if(!StringUtils.isEmpty(category.getArea())){
                entityWrapper.like("area",String.valueOf(category.getArea()));
            }
            if(!StringUtils.isEmpty(category.getIntroduce())){
                entityWrapper.like("introduce",String.valueOf(category.getIntroduce()));
            }
        }
        return entityWrapper;
    }

    public void modify(Category category) {
        categoryMapper.updateById(category);
    }

    public void add(Category category) {
        // 设置默认值：未删除
        category.setDeleted(0);
        categoryMapper.insert(category);
    }

    public Category findById(Integer id) {
        // 只查询未删除的房型
        List<Category> categories = categoryMapper.selectList(new EntityWrapper<Category>().eq("id", id).eq("deleted", 0));
        if (categories.isEmpty()) {
            return null;
        }
        Category c = categories.get(0);
        Integer count = roomMapper.selectCount(new EntityWrapper<Room>().eq("category_id", c.getId()).eq("status", 1).eq("deleted", 0));
        c.setRoomNum(count);
        return c;
    }

    public void removeById(Integer id) {
        // 检查是否存在关联的未删除房间
        Integer roomCount = roomMapper.selectCount(new EntityWrapper<Room>().eq("category_id", id).eq("deleted", 0));
        if (roomCount > 0) {
            throw new RuntimeException("该房型下还有 " + roomCount + " 个房间，无法删除！请先删除或转移相关房间。");
        }
        // 实现逻辑删除：将deleted字段设置为1
        Category category = new Category();
        category.setId(id);
        category.setDeleted(1);
        categoryMapper.updateById(category);
    }

    /**
     * 导出房型数据到Excel
     * @param category 查询条件
     * @param response HTTP响应
     * @throws IOException
     */
    public void exportCategoryData(Category category, HttpServletResponse response) throws IOException {
        // 查询数据
        List<Category> categoryList = search(category);

        // 创建工作簿
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("房型信息");

        // 创建标题行样式
        CellStyle headerStyle = workbook.createCellStyle();
        headerStyle.setFillForegroundColor(IndexedColors.BLUE.getIndex());
        headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        headerStyle.setBorderTop(BorderStyle.MEDIUM);
        headerStyle.setBorderBottom(BorderStyle.MEDIUM);
        headerStyle.setBorderLeft(BorderStyle.MEDIUM);
        headerStyle.setBorderRight(BorderStyle.MEDIUM);
        headerStyle.setAlignment(HorizontalAlignment.CENTER);
        headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        Font headerFont = workbook.createFont();
        headerFont.setBold(true);
        headerFont.setColor(IndexedColors.WHITE.getIndex());
        headerFont.setFontHeightInPoints((short) 12);
        headerStyle.setFont(headerFont);

        // 创建数据行样式
        CellStyle dataStyle = workbook.createCellStyle();
        dataStyle.setBorderTop(BorderStyle.THIN);
        dataStyle.setBorderBottom(BorderStyle.THIN);
        dataStyle.setBorderLeft(BorderStyle.THIN);
        dataStyle.setBorderRight(BorderStyle.THIN);
        dataStyle.setAlignment(HorizontalAlignment.CENTER);
        dataStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        // 创建价格样式（右对齐，保留两位小数）
        CellStyle priceStyle = workbook.createCellStyle();
        priceStyle.setBorderTop(BorderStyle.THIN);
        priceStyle.setBorderBottom(BorderStyle.THIN);
        priceStyle.setBorderLeft(BorderStyle.THIN);
        priceStyle.setBorderRight(BorderStyle.THIN);
        priceStyle.setAlignment(HorizontalAlignment.RIGHT);
        priceStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        DataFormat format = workbook.createDataFormat();
        priceStyle.setDataFormat(format.getFormat("¥#,##0.00"));

        // 创建数字样式（居中对齐）
        CellStyle numberStyle = workbook.createCellStyle();
        numberStyle.setBorderTop(BorderStyle.THIN);
        numberStyle.setBorderBottom(BorderStyle.THIN);
        numberStyle.setBorderLeft(BorderStyle.THIN);
        numberStyle.setBorderRight(BorderStyle.THIN);
        numberStyle.setAlignment(HorizontalAlignment.CENTER);
        numberStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        // 创建标题行
        Row headerRow = sheet.createRow(0);
        headerRow.setHeight((short) 600); // 设置标题行高度
        String[] headers = {"房型ID", "房型名称", "价格(元)", "可住人数", "床位数", "面积(㎡)", "房间数量", "介绍"};

        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
            cell.setCellStyle(headerStyle);
        }

        // 填充数据
        for (int i = 0; i < categoryList.size(); i++) {
            Row row = sheet.createRow(i + 1);
            row.setHeight((short) 450); // 设置数据行高度
            Category c = categoryList.get(i);

            // 房型ID
            Cell cell0 = row.createCell(0);
            cell0.setCellValue(c.getId());
            cell0.setCellStyle(numberStyle);

            // 房型名称
            Cell cell1 = row.createCell(1);
            cell1.setCellValue(c.getCategoryName() != null ? c.getCategoryName() : "未命名");
            cell1.setCellStyle(dataStyle);

            // 价格
            Cell cell2 = row.createCell(2);
            cell2.setCellValue(c.getPrice() != null ? c.getPrice().doubleValue() : 0);
            cell2.setCellStyle(priceStyle);

            // 可住人数
            Cell cell3 = row.createCell(3);
            cell3.setCellValue(c.getLiveNum() != null ? c.getLiveNum() : 0);
            cell3.setCellStyle(numberStyle);

            // 床位数
            Cell cell4 = row.createCell(4);
            cell4.setCellValue(c.getBedNum() != null ? c.getBedNum() : 0);
            cell4.setCellStyle(numberStyle);

            // 面积
            Cell cell5 = row.createCell(5);
            String area = c.getArea() != null && !c.getArea().trim().isEmpty() ?
                c.getArea() : "未知";
            cell5.setCellValue(area);
            cell5.setCellStyle(dataStyle);

            // 房间数量
            Cell cell6 = row.createCell(6);
            cell6.setCellValue(c.getRoomNum() != null ? c.getRoomNum() : 0);
            cell6.setCellStyle(numberStyle);

            // 介绍
            Cell cell7 = row.createCell(7);
            String introduce = c.getIntroduce() != null && !c.getIntroduce().trim().isEmpty() ?
                c.getIntroduce() : "暂无介绍";
            cell7.setCellValue(introduce);
            cell7.setCellStyle(dataStyle);
        }

        // 设置列宽（更精确的控制）
        sheet.setColumnWidth(0, 2500);  // 房型ID
        sheet.setColumnWidth(1, 4000);  // 房型名称
        sheet.setColumnWidth(2, 3500);  // 价格
        sheet.setColumnWidth(3, 3000);  // 可住人数
        sheet.setColumnWidth(4, 3000);  // 床位数
        sheet.setColumnWidth(5, 3500);  // 面积
        sheet.setColumnWidth(6, 3000);  // 房间数量
        sheet.setColumnWidth(7, 8000);  // 介绍

        // 冻结首行（标题行）
        sheet.createFreezePane(0, 1);

        // 设置响应头
        String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String fileName = "房型信息_" + timestamp + ".xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

        // 写入响应流
        workbook.write(response.getOutputStream());
        workbook.close();
    }
}
